<template>
	<view class="content">
		<view class="navbar">
			<view v-for="(item, index) in navList" :key="index" class="nav-item" :class="{current: tabCurrentIndex === index}"
			 @click="tabClick(index)">
				{{item.text}}
			</view>
		</view>

		<swiper :current="tabCurrentIndex" class="swiper-box" duration="300" @change="changeTab">
			<swiper-item class="tab-content" v-for="(tabItem,tabIndex) in navList" :key="tabIndex">
				<scroll-view class="list-scroll-content" scroll-y @scrolltolower="loadData('add')">
					<!-- 空白页 -->
					<empty v-if="refundList==null||refundList.length === 0"></empty>

					<!-- 退款列表 -->
					<view v-for="(item,index) in refundList" :key="index" class="order-item">
						<view class="i-top b-b">
							<text class="time" @click="showRefundDetail(item.id)">{{item.createTime | formatDateTime}}</text>
							<text class="state" :style="{color: getStatusColor(item.status)}">{{item.status | formatStatus}}</text>
							<text v-if="item.status===4" class="del-btn yticon icon-iconfontshanchu1" @click="deleteRefund(item.id)"></text>
						</view>
						<view class="goods-box-single" @click="showRefundDetail(item.id)">
							<image class="goods-img" :src="item.productPic" mode="aspectFill"></image>
							<view class="right">
								<text class="title clamp">{{item.productName}}</text>
								<text class="attr-box">退款原因：{{item.reason}}</text>
								<text class="price">￥{{item.refundAmount}}</text>
							</view>
						</view>

						<view class="price-box">
							<text class="label">退款单号：{{item.refundSn}}</text>
						</view>

						<view class="action-box b-t" v-if="item.status === 0">
							<button class="action-btn" @click="cancelRefundOrder(item.id)">取消申请</button>
							<button class="action-btn recom" @click="showRefundDetail(item.id)">查看进度</button>
						</view>
						<view class="action-box b-t" v-if="item.status === 1 || item.status === 2">
							<button class="action-btn recom" @click="showRefundDetail(item.id)">查看详情</button>
						</view>
					</view>

					<uni-load-more :status="loadingType"></uni-load-more>

				</scroll-view>
			</swiper-item>
		</swiper>
	</view>
</template>

<script>
	import uniLoadMore from '@/components/uni-load-more/uni-load-more.vue';
	import empty from "@/components/empty";
	import {
		formatDate
	} from '@/utils/date';
	import {
		fetchRefundList,
		cancelRefund
	} from '@/api/refund.js';

	export default {
		components: {
			uniLoadMore,
			empty
		},
		data() {
			return {
				tabCurrentIndex: 0,
				refundParam: {
					status: -1,
					pageNum: 1,
					pageSize: 10
				},
				refundList: [],
				loadingType: 'more',
				navList: [{
						state: -1,
						text: '全部'
					},
					{
						state: 0,
						text: '申请中'
					},
					{
						state: 2,
						text: '已完成'
					},
					{
						state: 4,
						text: '已取消'
					}
				],
			};
		},
		onLoad(options) {
			this.tabCurrentIndex = +options.state || 0;
			this.loadData();
		},
		filters: {
			formatStatus(status) {
				let statusTip = '';
				switch (+status) {
					case 0:
						statusTip = '退款申请中';
						break;
					case 1:
						statusTip = '商家已同意';
						break;
					case 2:
						statusTip = '退款成功';
						break;
					case 3:
						statusTip = '申请被拒绝';
						break;
					case 4:
						statusTip = '已取消';
						break;
				}
				return statusTip;
			},
			formatDateTime(time) {
				if (time == null || time === '') {
					return 'N/A';
				}
				let date = new Date(time);
				return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
			}
		},
		methods: {
			// 获取状态颜色
			getStatusColor(status) {
				switch (+status) {
					case 0:
						return '#ff9900'; // 申请中-橙色
					case 1:
						return '#5fcda2'; // 已同意-绿色
					case 2:
						return '#5fcda2'; // 退款成功-绿色
					case 3:
						return '#999999'; // 被拒绝-灰色
					case 4:
						return '#999999'; // 已取消-灰色
					default:
						return '#fa436a';
				}
			},

			// Tab切换
			tabClick(index) {
				this.tabCurrentIndex = index;
				this.switchTab(this.navList[index].state);
			},

			// Swiper切换
			changeTab(e) {
				this.tabCurrentIndex = e.target.current;
				this.switchTab(this.navList[e.target.current].state);
			},

			// 切换Tab
			switchTab(state) {
				this.refundParam.status = state;
				this.refundParam.pageNum = 1;
				this.refundList = [];
				this.loadingType = 'more';
				this.loadData();
			},

			// 加载数据
			loadData(type = 'refresh') {
				if (type === 'add') {
					if (this.loadingType !== 'more') {
						return;
					}
					this.refundParam.pageNum += 1;
				}

				this.loadingType = 'loading';

				fetchRefundList(this.refundParam).then(response => {
					if (response.data && response.data.list) {
						if (type === 'refresh') {
							this.refundList = response.data.list;
						} else {
							this.refundList = this.refundList.concat(response.data.list);
						}

						// 判断是否还有更多数据
						if (response.data.list.length < this.refundParam.pageSize) {
							this.loadingType = 'noMore';
						} else {
							this.loadingType = 'more';
						}
					} else {
						this.refundList = [];
						this.loadingType = 'noMore';
					}
				}).catch(err => {
					console.error('加载退款列表失败', err);
					this.loadingType = 'noMore';
					uni.showToast({
						title: '加载失败',
						icon: 'none'
					});
				});
			},

			// 查看退款详情
			showRefundDetail(refundId) {
				uni.navigateTo({
					url: `/pages/order/refundDetail?refundId=${refundId}`
				});
			},

			// 取消退款申请
			cancelRefundOrder(refundId) {
				uni.showModal({
					title: '提示',
					content: '确定要取消退款申请吗？',
					success: (res) => {
						if (res.confirm) {
							uni.showLoading({
								title: '处理中...'
							});

							cancelRefund(refundId).then(response => {
								uni.hideLoading();
								uni.showToast({
									title: '取消成功',
									icon: 'success'
								});
								this.loadData('refresh');
							}).catch(err => {
								uni.hideLoading();
								uni.showToast({
									title: err.message || '取消失败',
									icon: 'none'
								});
							});
						}
					}
				});
			},

			// 删除退款记录（仅UI删除）
			deleteRefund(refundId) {
				uni.showModal({
					title: '提示',
					content: '确定要删除该退款记录吗？',
					success: (res) => {
						if (res.confirm) {
							const index = this.refundList.findIndex(item => item.id === refundId);
							if (index > -1) {
								this.refundList.splice(index, 1);

								// 同步删除localStorage中的数据
								try {
									const storedData = uni.getStorageSync('refundList');
									if (storedData) {
										let allRefunds = JSON.parse(storedData);
										allRefunds = allRefunds.filter(item => item.id !== refundId);
										uni.setStorageSync('refundList', JSON.stringify(allRefunds));
									}
								} catch (e) {
									console.error('删除退款记录失败', e);
								}

								uni.showToast({
									title: '删除成功',
									icon: 'success'
								});
							}
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	.content {
		background: $page-color-base;
	}

	.navbar {
		display: flex;
		height: 80upx;
		padding: 0 10upx;
		background: #fff;
		box-shadow: 0 2upx 10upx rgba(0, 0, 0, .06);
		position: relative;
		z-index: 10;

		.nav-item {
			flex: 1;
			display: flex;
			justify-content: center;
			align-items: center;
			height: 100%;
			font-size: 30upx;
			color: $font-color-dark;
			position: relative;

			&.current {
				color: $base-color;

				&:after {
					content: '';
					position: absolute;
					left: 50%;
					bottom: 0;
					transform: translateX(-50%);
					width: 120upx;
					height: 4upx;
					background: $base-color;
					border-radius: 2upx;
				}
			}
		}
	}

	.swiper-box {
		height: calc(100vh - 80upx);
	}

	.list-scroll-content {
		height: 100%;
		padding: 0 30upx;
	}

	.order-item {
		display: flex;
		flex-direction: column;
		padding-bottom: 30upx;
		background: #fff;
		margin-top: 30upx;
		border-radius: 10upx;
		box-shadow: 0 4upx 20upx rgba(0, 0, 0, .06);

		.i-top {
			display: flex;
			align-items: center;
			height: 80upx;
			padding: 0 30upx;
			font-size: 26upx;

			.time {
				flex: 1;
				color: $font-color-light;
			}

			.state {
				font-size: 28upx;
				color: $base-color;
			}

			.del-btn {
				font-size: 36upx;
				color: $font-color-light;
				margin-left: 20upx;
			}
		}

		.goods-box-single {
			display: flex;
			padding: 20upx 30upx;

			.goods-img {
				display: block;
				width: 140upx;
				height: 140upx;
				border-radius: 8upx;
			}

			.right {
				flex: 1;
				display: flex;
				flex-direction: column;
				padding: 0 0 0 24upx;
				overflow: hidden;

				.title {
					font-size: 30upx;
					color: $font-color-dark;
					line-height: 1.5;
				}

				.attr-box {
					font-size: 24upx;
					color: $font-color-light;
					padding: 10upx 0;
				}

				.price {
					font-size: 30upx;
					color: $base-color;
					font-weight: bold;
				}
			}
		}

		.price-box {
			display: flex;
			justify-content: flex-end;
			align-items: center;
			padding: 20upx 30upx 0;
			font-size: 24upx;
			color: $font-color-light;

			.label {
				flex: 1;
			}

			.num {
				margin: 0 4upx;
			}

			.price {
				font-size: 32upx;
				color: $base-color;
				font-weight: bold;
			}
		}
	}

	.action-box {
		display: flex;
		justify-content: flex-end;
		align-items: center;
		height: 100upx;
		position: relative;
		padding-right: 30upx;
	}

	.action-btn {
		width: 160upx;
		height: 60upx;
		margin: 0;
		margin-left: 24upx;
		padding: 0;
		text-align: center;
		line-height: 60upx;
		font-size: $font-sm + 2upx;
		color: $font-color-dark;
		background: #fff;
		border-radius: 100px;

		&:after {
			border-radius: 100px;
		}

		&.recom {
			background: #fff9f9;
			color: $base-color;

			&:after {
				border-color: #f7bcc8;
			}
		}
	}
</style>
